<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="width: 70%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      class="info"
      v-loading="formLoading"
    >
      <el-form-item :label="t('opticore.route.form.code')" prop="routeCode">
        <el-input v-model="formData.routeCode" :placeholder="t('opticore.route.form.codePlaceholder')" disabled />
      </el-form-item>
      <el-form-item :label="t('opticore.route.form.name')" prop="routeName">
        <el-input v-model="formData.routeName" :placeholder="t('opticore.route.form.namePlaceholder')" />
      </el-form-item>
      <el-form-item :label="t('opticore.route.form.status')" prop="status">
        <el-switch v-model="formData.status" active-color="#13ce66" inactive-color="#ff4949" />
      </el-form-item>
      <el-form-item :label="t('opticore.route.form.errorPrevention')" prop="switchStatus">
        <el-switch
          v-model="switchStatus"
          @change="changeSwitch"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </el-form-item>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane :label="t('opticore.route.tabs.processPath')" name="routeProcessRel">
        <RouteProcessRelForm
          ref="routeProcessRelFormRef"
          @sendStatus="getStatus"
          :switchStatus="switchStatus"
          :route-id="formData.id"
        />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('opticore.route.action.confirm') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('opticore.route.action.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { RouteApi, RouteVO } from '@/api/opticore/route'
import RouteProcessRelForm from './components/RouteProcessRelForm.vue'

/** 工艺路线信息 表单 */
defineOptions({ name: 'RouteForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  routeCode: undefined,
  routeName: undefined,
  status: undefined,
  index: undefined
})
const formRules = reactive({
  routeCode: undefined,
  routeName: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('routeProcessRel')
const routeProcessRelFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const res = await RouteApi.getRoute(id)

      formData.value = { ...res, status: res.status == 1 ? true : false }
    } finally {
      formLoading.value = false
    }
  }else{
    switchStatus.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const switchStatus = ref()

const changeSwitch = (val) => {
  routeProcessRelFormRef.value.allSelect(val)
}

const getStatus = (val) => {
  console.log(999,val);
  
  switchStatus.value = val

  // formData.value = { ...formData.value, status: val }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await routeProcessRelFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'routeProcessRel'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RouteVO
    // 拼接子表的数据
    data.routeProcessRels = routeProcessRelFormRef.value.getData()
    let valOj = Object.assign(
      data,
      { status: data.status ? 1 : 0 },
      {
        routeProcessRels: data.routeProcessRels.map((item) => {
          return {
            ...item,
            errorPrevention: item?.errorPrevention ? 1 : 0
          }
        })
      }
    )
    if (formType.value === 'create') {
      await RouteApi.createRoute(valOj)
      message.success(t('common.createSuccess'))
    } else {
      await RouteApi.updateRoute(valOj)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    routeCode: undefined,
    routeName: undefined,
    status: undefined,
    index: undefined
  }
  formRef.value?.resetFields()
}
</script>
<style scoped>
.info {
  display: flex;
}
</style>
